<template>
  <view class="buy-wrapper">
    <view class="pay-title">请使用支付宝扫码支付</view>
    <view class="qrcode-container">
      <canvas canvas-id="pay-qrcode" style="width: 300px; height: 300px; margin-bottom: 40rpx;" />
    </view>
    <view class="pay-amount">支付金额：￥{{ amount }}</view>
    <view class="countdown-box">支付倒计时：{{ countdown }} 秒</view>
  </view>
</template>

<script setup>
import { ref, watch, onMounted, onUnmounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import uQRCode from '../../uni_modules/cc-defineQRCode/components/cc-defineQRCode/common/uqrcode.js'

const qrCodeContent = ref('hello world')
const amount = ref('')
const countdown = ref(60)
let timer = null
let pollTimer = null
const outTradeNo = ref('') // 假设你有订单号，实际可根据后端返回赋值

const generateQRCode = () => {
  if (!qrCodeContent.value) return
  uni.showLoading({
    title: '二维码生成中',
    mask: true
  })
  uQRCode.make({
    canvasId: 'pay-qrcode',
    text: qrCodeContent.value,
    size: 300,
    margin: 10,
    success: res => {
      console.log('二维码生成成功', res)
    },
    fail: err => {
      console.error('二维码生成失败', err)
    },
    complete: () => {
      uni.hideLoading()
    }
  })
}

onLoad((options) => {
  amount.value = options.amount || '0.00'
  uni.request({
    url: 'http://localhost:1011/api/alipay/pay',
    method: 'POST',
    header: {
      'content-type': 'application/json',
      'token': 'test-token'
    },
    data: {
      orderPrice: options.price,
      idleItem: '在线问诊',
      userId: 1,
	    orderId: 'fae1d659a-7a1e-4054-bb91-2a1017f88dc5'
    },
    success: (res) => {
      // 兼容字符串和对象返回
      let data = res.data
      if (typeof data === 'string') {
        try {
          data = JSON.parse(data)
        } catch (e) {
          console.error('返回数据不是有效的JSON', data)
        }
      }
      qrCodeContent.value = data.qrCode
      outTradeNo.value = data.outTradeNo
      console.log('所有二维码内容', qrCodeContent)
      console.log('二维码内容', qrCodeContent.value)
      console.log('订单号', outTradeNo.value)
      generateQRCode()
    },
    fail: () => {
      uni.showToast({ title: '二维码生成失败', icon: 'none' })
    }
  })
  timer = setInterval(() => {
    if (countdown.value > 0) {
      countdown.value--
    } else {
      clearInterval(timer)
    }
  }, 1000)

  // 每5秒轮询订单状态
  pollTimer = setInterval(() => {
    console.log('开始轮询订单', outTradeNo.value)
    if (outTradeNo.value) {
      uni.request({
        url: 'http://localhost:1011/api/order/status',
        method: 'POST',
        header: {
          'content-type': 'application/json'
        },
        data: {
          outTradeNo: outTradeNo.value,
          orderPrice: amount.value,
          idleItem: '在线问诊',
          userId: 1
        },
        success: (res) => {
          console.log('订单状态：', res.data)
        },
        fail: (err) => {
          console.error('查询订单状态失败', err)
        }
      })
    }
  }, 5000)
})

onUnmounted(() => {
  if (timer) clearInterval(timer)
  if (pollTimer) clearInterval(pollTimer)
})

// 若二维码内容后续会变化，也可用watch自动生成
watch(qrCodeContent, (val) => {
  if (val) generateQRCode()
})
</script>

<style>
.buy-wrapper {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 80rpx;
}
.pay-title {
  font-size: 36rpx;
  margin-bottom: 40rpx;
}
.qrcode-container {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 40rpx;
}
.pay-amount {
  font-size: 32rpx;
  color: #333;
}
.countdown-box {
  width: 80%;
  height: 50rpx;
  border: 2rpx solid #f00;
  border-radius: 10rpx;
  margin-top: 20rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #f00;
  font-size: 32rpx;
  background: #fff;
}
</style> 